﻿/* *************************************************
 *  Copyright © FlexDev 2010. All rights reserved.
 *  Author: Rodrigo da Silva Brito
 *  Date: 07/16/2010
 *  Contact: mailto:rodrigosilvabrito@hotmail.com
 *  Site: http://www.flexdev.com.br
 * *************************************************
*/
using System.ServiceModel.Channels;
using System.Xml;
using Flexdev.Security;

namespace Flexdev.Wcf.Extensions
{
    public class FlexdevHeader : MessageHeader
    {
        public const string PasswordKey = "$%vedxelfbrito!@";

        public FlexdevHeader()
        {
        }

        public FlexdevHeader(string userName, string password)
        {
            this.userName = userName;
            this.password = password;
        }

        protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
        {
            writer.WriteStartElement(FlexdevHeaderNames.SecurityHeaderName);
            writer.WriteElementString(FlexdevHeaderNames.UserName, this.userName);
            writer.WriteElementString(FlexdevHeaderNames.Password, this.password);
            writer.WriteEndElement();
        }

        public override string Name
        {
            get { return FlexdevHeaderNames.HeaderName; }
        }

        public override string Namespace
        {
            get { return FlexdevHeaderNames.HeaderNameSpace; }
        }

        private string userName = string.Empty;
        public string UserName
        {
            get { return userName; }
            set { userName = value; }
        }

        private string password = string.Empty;
        public string Password
        {
            get { return password; }
            set { password = value; }
        }

        public static FlexdevHeader ReadHeader(XmlDictionaryReader reader)
        {
            string userName = string.Empty;
            string password = string.Empty;

            // Read the header content (Security) using the XmlDictionaryReader
            if (reader.ReadToDescendant(FlexdevHeaderNames.SecurityHeaderName, FlexdevHeaderNames.HeaderNameSpace))
            {
                if (reader.ReadToDescendant(FlexdevHeaderNames.UserName))
                {
                    userName = CryptService.Decrypt(reader.ReadElementContentAsString(FlexdevHeaderNames.UserName, FlexdevHeaderNames.HeaderNameSpace), PasswordKey, AesCryptographyLevel.AES_256);
                    password = CryptService.Decrypt(reader.ReadElementContentAsString(FlexdevHeaderNames.Password, FlexdevHeaderNames.HeaderNameSpace), PasswordKey, AesCryptographyLevel.AES_256);
                }

                return (new FlexdevHeader(userName, password));
            }

            return null;
        }
    }
}
